package cn.lx.queue;

import java.util.Iterator;


/** 使用链表实现先进先进队列
 * 由于需要实现先进先出，所以需要维护首节点和末节点对象
 * Created by Administrator on 2017/3/21 0021.
 */
public class MyNodeQueue<Item> implements Iterable<Item>{
    Node first;
    Node last;
    int N;

    @Override
    public Iterator iterator() {
        return new MyNodeQueueIterator();
    }
    private class MyNodeQueueIterator implements Iterator<Item>{
        int i = N;
        Node next = first;
        @Override
        public boolean hasNext() {
            return i >0;
        }

        @Override
        public Item next() {
            Item item = next.item;
            next = next.next;
            i--;
            return item;
        }
    }
    private class Node{
        Node next;
        Item item;
    }

    public void enqueue(Item item){
        Node oldLast =last;
        last = new Node();
        last.item = item;

        /**
         * 第一次添加的时候，只有一个元素，first = last
            之后添加的时候，oldLast就是上一个元素了
         */
        if(isEmpty()){
            first = last;
        }else{
            oldLast.next = last;
        }

        N++;
    }

    public Item dequeue(){
        if(N == 0){
            return  null;
        }
        Node lastFirst = first;
        Item item = first.item;
        first = first.next;

        //当还有一个元素的时候first = last
        //当没有元素的时候这是first 为null，所以需要把last也置为null

        if(isEmpty()){
            last = null;
        }
        return item;
    }
    public boolean isEmpty(){
        return  N==0;
    }
    public int size(){
        return N;
    }
    public static void main(String[] args) {
        MyNodeQueue<String> stack = new MyNodeQueue<>();
        stack.enqueue("1");
        stack.enqueue("2");
        stack.enqueue("3");
        for(String s : stack){
            System.out.println(s);
        }
    }
}
